package jtech;

import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.LinkedList;

public class GameOutputStream extends OutputStream {

	private Font font = Drawer.FONT_DEFAULT;
	private int align = Drawer.ALIGN_LEFT;
	private Color color = Color.WHITE;
	private float sx = 10;
	private float sy = 10;
	
	private int maxLines = 15;
	private int wait = 3;
	
	private StringBuilder line = new StringBuilder();
	private LinkedList<LineColor> lines = new LinkedList<LineColor>();
	
	
	
	private class LineColor {
		String text;
		float delay;
	}

	@Override
	public void write(int b) throws IOException {
		if (b == '\n' || b == '\r'){
			return;
		}
		line.append((char) b);
	}

	@Override
	public void flush() throws IOException {
		if (line.length() == 0) {
			return;
		}
		
		LineColor lc = new LineColor();
		lc.text  = line.toString();
		lc.delay = Game.getTime() + wait + (.5f*lines.size());
		
		line.setLength(0);
		
		lines.addLast(lc);
		if (lines.size() > maxLines) {
			lines.removeFirst();
		}
	}
	
	public void draw(Drawer drawer) {
		drawer.align(align);
		drawer.font(font);
		
		int offset = 0;
		int height = drawer.getG2D().getFontMetrics().getHeight();
		
		Iterator<LineColor> i = lines.iterator();
		while (i.hasNext()) {
			LineColor lc = i.next();
			drawer.color(color);
			drawer.print(sx, sy + (offset*height), lc.text);
			offset++;
			if (lc.delay <= Game.getTime()) {
				i.remove();
			}
		}
	}
	
}
